
import java.util.*;

public class Solution {
    class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> ans = new ArrayList<>();
        if(root == null){
            return ans;
        }
        stack.add(root);
        while(!stack.isEmpty()){
            TreeNode tmp = stack.pop();
            ans.add(tmp.val);
            if(tmp.left != null){
                stack.add(tmp.left);
            }
            if(tmp.right != null){
                stack.add(tmp.right);
            }
        }
        Collections.reverse(ans);
        return ans;
    }
}
